package com.tiancai.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiancai.context.BaseContext;
import com.tiancai.enums.PayStatus;
import com.tiancai.enums.PayType;
import com.tiancai.pojo.dto.OrderDto;
import com.tiancai.pojo.po.Orders;
import com.tiancai.pojo.po.User;
import com.tiancai.pojo.po.Work;
import com.tiancai.pojo.po.WorkRent;
import com.tiancai.pojo.vo.OrderVo;
import com.tiancai.result.Result;
import com.tiancai.service.IOrderService;
import com.tiancai.service.IUserService;
import com.tiancai.service.IWorkRentService;
import com.tiancai.service.IWorkService;
import com.tiancai.webSocket.WebSocketServer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tiancai
 * @since 2025-03-17
 */
@RestController
@RequestMapping("/order")
@Tag(name = "订单管理")
@Slf4j
@CrossOrigin
public class OrderController {
    @Autowired
    private IOrderService orderService;

    @Autowired
    private IUserService userService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private IWorkService workService;

    @Autowired
    private IWorkRentService workRentService;

    // 新增订单
    @PostMapping("/add")
    @Operation(summary = "购买作品生成订单")
    public Result<Orders> add(@RequestBody OrderDto orderDto) {
        Orders orders = orderService.add(orderDto);
        // 查找订单里的作品
        Work work = workService.getById(orders.getProductId());
        // 如果订单是租赁,则新增租赁
        if (orderDto.getType().equals(PayType.RENT)) {
            // 新增租赁
            WorkRent workRent = WorkRent.builder()
                    .workId(work.getId())
                    .userId(BaseContext.getCurrentId())
                    .build();
            workRentService.save(workRent);
        } else {
            // 把作品的作者改为当前用户
            work.setUserId(BaseContext.getCurrentId());
            workService.updateById(work);
        }
        return Result.success(orders);
    }

    // 查看订单
    @GetMapping("/{id}")
    @Operation(summary = "查看订单")
    public Result<OrderVo> get(@PathVariable Long id) {
        OrderVo orderVo = orderService.getOrderById(id);
        return Result.success(orderVo);
    }

    // 删除订单
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除订单")
    public Result delete(@PathVariable Long id) {
        orderService.removeById(id);
        return Result.success();
    }

    // 退款订单
    @PostMapping("/refund/{id}")
    @Operation(summary = "退款订单")
    public Result<Orders> refund(@PathVariable Long id) {
        Orders orders = orderService.getById(id);
        // 根据订单查找作品id
        Work work = workService.getById(orders.getProductId());
        // 如果订单是租赁,则删除租赁
        if (orders.getType().equals(PayType.RENT)) {
            // 删除租赁
            workRentService.lambdaUpdate()
                    .eq(WorkRent::getUserId, BaseContext.getCurrentId())
                    .eq(WorkRent::getWorkId, orders.getProductId())
                    .remove();
        } else {
            // 把作品的用户改为原始用户
            work.setUserId(work.getOrginUserId());
            workService.updateById(work);
        }
        orders.setPayStatus(PayStatus.REFUND);
        orderService.updateById(orders);
        return Result.success(orders);
    }

    // 查看当前用户的所有订单
    @GetMapping("/getAll")
    @Operation(summary = "查看当前用户的所有订单")
    public Result<Page<OrderVo>> getAll(@RequestParam(value = "currPage", defaultValue = "1") Integer page,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        // 获取当前用户的 ID
        Long currentUserId = BaseContext.getCurrentId();

        // 查询当前用户的所有订单，并转换为 OrderVo 列表
        List<OrderVo> orderVoList = orderService.lambdaQuery()
                .eq(Orders::getCustomerId, currentUserId) // 过滤当前用户的订单
                .list()
                .stream()
                .map(order -> {
                    User seller = userService.getById(order.getSellerId());
                    return OrderVo.builder()
                            .createTime(order.getCreateTime())
                            .code(order.getCode())
                            .type(order.getType())
                            .workId(order.getProductId())
                            // .price()
                            .currency(order.getCurrency())
                            .sellerName(seller.getUsername())
                            .workName(workService.getById(order.getProductId()).getTitle())
                            .payMethod(order.getPayMethod())
                            .payStatus(order.getPayStatus())
                            .build();
                })
                .collect(Collectors.toList());
        Page<OrderVo> pageResult = new Page<>(page, pageSize);
        pageResult.setRecords(orderVoList);
        pageResult.setTotal(orderVoList.size());

        return Result.success(pageResult);
    }
}

